import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-resource-page',
  templateUrl: './resource-page.component.html',
  styleUrls: ['./resource-page.css']
})
export class ResourcePageComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      sourceKey: {
        validators: {
          notEmpty: {
            message: '请输入资源标识'
          }
        }
      },
      name: {
        validators: {
          notEmpty: {
            message: '请输入资源名称'
          },
          stringLength: {
            max: 30,
            message: '资源名称30字以内'
          }
          //					remote: {
          //			            message: '资源名称已存在',
          //			            url: config.BaseURL+"resource/validateResourceName.html",
          //			            data: function(validator) {
          //                          return {
          //                              id: validator.getFieldElements('name').attr("resourceId")
          //                          };
          //                      },
          //		        	}
        }
      }
      // path: {
      // 	validators: {
      // 		notEmpty: {
      // 			message: '请输入资源path'
      // 		}
      // 	}
      // },
    }
  }
  page: any = {
    type: 0,
    resourceType: 0,
    parentId: '',
    name: '',
    sourceKey: '',
    sourceUrl: '',
    path: '',
    icon: '',
    description: '',
    indexNum: ''
  }
  typeList = [
    {
      value: 0,
      label: '菜单'
    },
    {
      value: 1,
      label: '按钮'
    }
  ]
  resourceTypeList = [
    {
      value: 0,
      label: '默认'
    },
    {
      value: 1,
      label: '新汉德平台'
    },
    {
      value: 2,
      label: '供应链'
    },
    {
      value: 3,
      label: '商城'
    }
  ]
  page_title: string = '新增'
  pageType: string = 'new'
  curPage = 0 //页码缓存
  resourceId = ''
  selectMenus = '' //菜单选中显示值
  timer: any
  resourceList = [] //jstree

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.resourceId = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
  }
  typeChange(e) {
    this.page.type = +e
    $('#resourceForm').data('bootstrapValidator').resetForm()
  }
  resourceTypeChange(e) {
    this.page.resourceType = +e
    $('#tree').jstree(true).refresh()
    $('#resourceForm').data('bootstrapValidator').resetForm()
  }
  //表单校验
  onSubmit() {
    $('#resourceForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#resourceForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.updata()
    }
  }
  //图标icon选中回调
  iconClick() {
    $('#dialog').toggleClass('dialog-open')
  }
  //表单数据提交
  updata() {
    var reqdata = '',
      url
    if(!this.page.indexNum && this.page.indexNum !== 0) {
      this.page.indexNum = ''
    }
    for (let item in this.page) {
      reqdata += item + '=' + this.page[item] + '&'
    }
    reqdata = reqdata.substring(0, reqdata.length - 1)
    if (this.pageType === 'new') {
      url = 'resource/add.html'
    } else if (this.pageType === 'updata') {
      reqdata = reqdata + '&id=' + this.resourceId
      url = 'resource/edit.html'
    }
    if (+this.page.indexNum < 0) {
      this.jsonApiService.message('序号不能小于0')
      return
    }

    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.router.navigate(['/system/resource'], { queryParams: { nowPage: this.curPage } })
      }
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/system/resource'], { queryParams: { nowPage: this.curPage } })
  }
  ngOnInit() {
    var that = this
    $('#dialog')
      .find('li')
      .each(function () {
        $(this).bind('click', function (e) {
          var icon = $(this).find('i').attr('class').replace('fa-3x', '')
          that.page.icon = icon
          $('#dialog').toggleClass('dialog-open')
        })
      })
    if (this.pageType === 'updata') {
      this.page_title = '编辑'
      let reqdata = 'id=' + this.resourceId
      this.jsonApiService.http('resource/resourceInfo.html', reqdata).subscribe(data => {
        if (data.success) {
          for (let item in this.page) {
            if (item == 'type' || item == 'resourceType') {
              this.page[item] = data.data[item]
            } else {
              this.page[item] = data.data[item] || ''
            }
          }
        } else {
          this.jsonApiService.message(data.message)
        }
        this.treeDataLoad()
      })
    } else {
      this.treeDataLoad()
    }
  }

  // 加载树形
  treeDataLoad() {
    System.import('assets/js/jstree/jstree.min.js').then(() => {
      this.load_company().then(() => {
        var tree_box = document.getElementById('tree_box')
        var company = document.getElementById('company')
        document.onclick = function (e: any) {
          if (
            !(
              e.target === company ||
              e.target.className === 'jstree-children' ||
              e.target.className === 's_del_icon' ||
              e.target.className === 'jstree-node  jstree-leaf' ||
              e.target.className === 'jstree-icon jstree-ocl' ||
              e.target.className === 'vision_tree' ||
              e.target.className === 'jstree-node jstree-leaf jstree-closed' ||
              e.target.className == 'treeSearchInput'
            )
          ) {
            tree_box.className = tree_box.className.replace('tree_open', '')
          }
        }
        this.resourceList.forEach(item => {
          if (item.id === this.page.parentId) {
            this.selectMenus = item.name
          }
        })
      })
    })
  }

  //公司树显示隐藏事件
  companyClick() {
    $('#tree_box').toggleClass('tree_open')
  }
  //擦除公司所选值
  delText() {
    $('#company').val('')
    $('#company').val('').change()
    if ($('#tree_box')[0].className.indexOf('tree_open') > 0) {
      $('#company').focus()
    }
  }
  //拉取上级名称树数据
  load_company() {
    var that = this
    return new Promise(function (resolve, reject) {
      $('#tree')
        .jstree({
          core: {
            data: function (obj, callback) {
              var jsonstr = '[]'
              var jsonarray = eval('(' + jsonstr + ')')
              var url = 'resource/resourceList.html'
              $.ajax({
                type: 'GET',
                url: config.BaseURL + url + '?resourceType=' + that.page.resourceType,
                dataType: 'json',
                xhrFields: {
                  withCredentials: true
                },
                success: function (result) {
                  jsonarray = result.data
                  that.resourceList = jsonarray
                  jsonarray.map(item => {
                    if (!item.parentId) {
                      item.parent = '#'
                    } else {
                      item.parent = item.parentId
                    }
                    item.text = item.name
                    item.state = { disabled: false, opened: true, selected: false }
                  })
                  resolve()
                  callback.call(this, jsonarray)
                }
              })
            },
            error: function (err) {
              console.log(err, 'err')
            },
            themes: {
              responsive: true
            },
            multiple: false,
            animation: 200,
            dblclick_toggle: true,
            expand_selected_onload: true
          },
          plugins: ['search']
        })
        .bind('activate_node.jstree', function (e, obj) {
          var currentNode = obj.node // 获取当前节点
          that.page.parentId = currentNode.id
          $('#company').val(currentNode.text).change()
        })
    })
  }
  //公司树模糊搜索
  companySearch() {
    var that = this
    var value = $('#tree_box').find('.treeSearchInput').val()
    $('#tree_box').find('#tree').eq(0).jstree(true).search(value)
    let searchResult = $('#tree_box').find('.jstree-search').length
    if (searchResult < 1) {
      return
    }
    $('#tree_box')
      .find('.jstree-search')
      .each(function (index, obj) {
        if (index < 1) {
          //js树搜索定位到结果的第一个地方；
          let container = $('#tree_box').find('.vision_tree')
          let scrollTo = $(this)
          container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
          container.animate({
            scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
          })
        }
      })
  }
  //公司树模糊搜索	click
  companySearchBtn() {
    var that = this
    var value = $('#tree_box').find('.treeSearchInput').val()
    $('#tree_box').find('#tree').eq(0).jstree(true).search(value)
    let searchResult = $('#tree_box').find('.jstree-search').length
    if (searchResult < 1) {
      that.jsonApiService.message('未搜索到结果')
      return
    }
    $('#tree_box')
      .find('.jstree-search')
      .each(function (index, obj) {
        if (index < 1) {
          //js树搜索定位到结果的第一个地方；
          let container = $('#tree_box').find('.vision_tree')
          let scrollTo = $(this)
          container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
          container.animate({
            scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
          })
        }
      })
  }
}
